<template>
  <div class="index">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-input" @click="goToSearch">
        <span class="iconfont icon-search">🔍</span>
        <span class="placeholder">搜索商品</span>
      </div>
    </div>

    <!-- 轮播图 -->
    <div class="banner-section">
      <div class="banner-container">
        <div 
          class="banner-item" 
          v-for="(banner, index) in banners" 
          :key="banner.id"
          v-show="index === currentBannerIndex"
          :class="{ active: index === currentBannerIndex }"
          @click="handleBannerClick(banner)"
        >
          <img 
            v-if="banner.imageUrl" 
            :src="banner.imageUrl" 
            :alt="banner.title"
            class="banner-image"
            @error="handleBannerImageError"
          />
          <div 
            v-else 
            class="banner-placeholder" 
            :style="{ background: getGradientColor() }"
          >
            {{ banner.title }}
          </div>
        </div>
      </div>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <div 
        class="category-item" 
        v-for="category in categories" 
        :key="category.id"
        @click="goToCategory(category)"
      >
        <div class="category-icon">{{ category.icon }}</div>
        <span>{{ category.name }}</span>
      </div>
    </div>

    <!-- 热门商品 -->
    <div class="section">
      <div class="section-header">
        <h2 class="section-title">热门商品</h2>
        <span class="section-more" @click="goToMore('hot')">查看更多</span>
      </div>
      <div class="products-grid">
        <div 
          class="product-card" 
          v-for="product in hotProducts" 
          :key="product.id"
          @click="goToProduct(product.id)"
        >
          <div class="product-image">
            <img 
              :src="product.mainImage || '/placeholder.svg'" 
              :alt="product.name"
              @error="handleProductImageError"
            />
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最新商品 -->
    <div class="section">
      <div class="section-header">
        <h2 class="section-title">最新商品</h2>
        <span class="section-more" @click="goToMore('new')">查看更多</span>
      </div>
      <div class="products-grid">
        <div 
          class="product-card" 
          v-for="product in newProducts" 
          :key="product.id"
          @click="goToProduct(product.id)"
        >
          <div class="product-image">
            <img 
              :src="product.mainImage || '/placeholder.svg'" 
              :alt="product.name"
              @error="handleProductImageError"
            />
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { getHotProducts, getNewProducts } from '@/api/product'
import { getActiveBanners } from '@/api/banner'
import { getActiveCategories } from '@/api/category'
import { showFullscreenLoading } from '@/utils/loading'

const router = useRouter()

// 响应式数据
const hotProducts = ref([])
const newProducts = ref([])
const banners = ref([])
const categories = ref([])
const currentBannerIndex = ref(0)
const bannerInterval = ref(null)

// 方法
const loadData = async () => {
  const loading = showFullscreenLoading({
    text: '正在加载数据...'
  })
  
  try {
    // 并行加载数据
    const [hotResponse, newResponse, bannersResponse, categoriesResponse] = await Promise.all([
      getHotProducts(),
      getNewProducts(),
      getActiveBanners(),
      getActiveCategories()
    ])
    
    if (hotResponse.data.success) {
      hotProducts.value = hotResponse.data.data || []
    }
    
    if (newResponse.data.success) {
      newProducts.value = newResponse.data.data || []
    }
    
    if (bannersResponse.data.success) {
      banners.value = bannersResponse.data.data || []
      console.log('轮播图数据加载成功:', banners.value)
    }

    if (categoriesResponse.data.success) {
      categories.value = categoriesResponse.data.data || []
      console.log('分类数据加载成功:', categories.value)
    }
  } catch (error) {
    console.error('加载首页数据失败:', error)
  } finally {
    loading.close()
  }
}

const startBannerAutoPlay = () => {
  if (banners.value.length > 1) {
    bannerInterval.value = setInterval(() => {
      currentBannerIndex.value = (currentBannerIndex.value + 1) % banners.value.length
    }, 3000)
  }
}

const stopBannerAutoPlay = () => {
  if (bannerInterval.value) {
    clearInterval(bannerInterval.value)
    bannerInterval.value = null
  }
}

const handleBannerClick = (banner: any) => {
  if (banner.link) {
    router.push(banner.link)
  }
}

const handleBannerImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

const handleProductImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder.svg'
}

const getGradientColor = () => {
  const gradients = [
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
  ]
  return gradients[Math.floor(Math.random() * gradients.length)]
}

const goToSearch = () => {
  router.push('/search')
}

const goToCategory = (category: any) => {
  router.push(`/category/${category.id}`)
}

const goToProduct = (productId: number) => {
  router.push(`/product/${productId}`)
}

const goToMore = (type: string) => {
  router.push(`/category?type=${type}`)
}

// 生命周期
onMounted(() => {
  loadData()
})

onUnmounted(() => {
  stopBannerAutoPlay()
})

// 监听banners数据变化，启动自动播放
import { watch } from 'vue'
watch(banners, (newBanners) => {
  if (newBanners.length > 0) {
    startBannerAutoPlay()
  }
}, { immediate: true })
</script>

<style scoped>
.index {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  padding: 20px;
  background-color: #fff;
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 12px 16px;
  border-radius: 20px;
  cursor: pointer;
}

.search-input .iconfont {
  margin-right: 8px;
  color: #999;
}

.placeholder {
  color: #999;
  font-size: 14px;
}

.banner-section {
  height: 200px;
  overflow: hidden;
  position: relative;
  background-color: #fff;
  margin-bottom: 20px;
}

.banner-container {
  width: 100%;
  height: 100%;
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.banner-item {
  width: 100%;
  height: 100%;
  cursor: pointer;
  flex-shrink: 0;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.category-nav {
  display: flex;
  flex-wrap: wrap;
  padding: 20px;
  background-color: #fff;
  margin-bottom: 20px;
}

.category-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.category-item:hover {
  transform: translateY(-2px);
}

.category-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.category-item span {
  font-size: 12px;
  color: #333;
}

.section {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.section-more {
  font-size: 14px;
  color: #007aff;
  cursor: pointer;
}

.products-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.product-card {
  width: calc(50% - 20px);
  margin: 10px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.product-card:hover {
  transform: translateY(-2px);
}

.product-image {
  width: 100%;
  height: 150px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 12px;
}

.product-name {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-price {
  font-size: 16px;
  color: #ff3b30;
  font-weight: bold;
  margin-top: 8px;
}

.current-price {
  font-size: 16px;
  color: #ff3b30;
  font-weight: bold;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
  margin-left: 8px;
}
</style> 